import React, { Component } from 'react';
import {
  View, Image, Dimensions, ScrollView,
  DeviceEventEmitter, TouchableNativeFeedback, Alert,
  TouchableWithoutFeedback,
} from 'react-native';
import {
  Text, Tab, Tabs, Badge,
} from 'native-base';
import DeviceInfo from 'react-native-device-info';

import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';

import Tab1 from './detailBaseInfo';
import Tab2 from './detailHandleInfo';
import { FormSearchChoice } from '../../../components';
import { commonMethods } from '../../../utils';
import { UtilToast, getCurrentPosition } from '../../../utils/util-method';
import * as incidentServer from '../../../services/incidentRequest';
import styles from './incidentInfo.style';
import * as todoService from '../../../services/todo';

import PollingRecord from '../../pollingRecord';

const fontColor = '#ffffff';
const deviceWidth = Dimensions.get('window').width;
class Info extends Component {
  static navigationOptions = {
    header: null,
  }

  searchUri = `${todoService.serverName}/device/fualt/queryMaintOrg`;

  swipeToDetailListhener = null;

  // 手机信息
  _mobileInfo = {};

  constructor(props) {
    super(props);
    this.state = {
      btnType: '100',
      timeLineLoading: false,
      pageData: {},
      changeParts: [],
      failurePositions: [],
      tab2Data: {},
      incidentId: '',
      fromNavigation: false,
      modalVisible: false,
      defaultPageIndex: 0,
    };
  }

  componentDidMount() {
    this._getMobileInfo();
    if (this.props.navigation) { // 路由带入参数
      this._initPage(this.props.navigation.state.params);
    } else {
      this.swipeToDetailListhener = DeviceEventEmitter.addListener('swipeToDetail', this._initPage);
    }
  }

  componentWillUnmount() {
    this.setState({
      modalVisible: false,
    });
    if (this.swipeToDetailListhener) {
      this.swipeToDetailListhener.remove();
    }
  }

  /**
   * 获取手机信息
  */
  _getMobileInfo = async () => {
    try {
      const macAddress = await DeviceInfo.getMACAddress().then(mac => mac);
      this._mobileInfo = {
        carrier: DeviceInfo.getCarrier(), // 运营商
        mac: macAddress, // mac地址
        mobileModel: `${DeviceInfo.getBrand()} / ${DeviceInfo.getModel()}`, // 手机型号
      };
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 通过故障单ID和跳转形式初始化页面和返回处理
  */
  _initPage = (params) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      this.setState({
        defaultPageIndex: 0,
      });
      if (commonMethods.isEmpty(params)) {
        UtilToast('无数据！', 'danger');
        DeviceEventEmitter.emit('showLoading', false);
        return;
      }
      const { id, fromNavigation, code } = params;
      this.setState({
        incidentId: id,
        incidentCode: code,
        fromNavigation,
      });
      this._getTab1Info(code);
      this._getTab2Info(id);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  _refresh = () => {
    DeviceEventEmitter.emit('refreshPageEvent'); // 刷新首页列表
    this._initPage({
      fromNavigation: this.state.fromNavigation,
      id: this.state.incidentId,
      code: this.state.incidentCode,
    });
  }

  // 获取基本信息
  _getTab1Info = async (code) => {
    try {
      const param = {
        failureCode: code,
      };
      const resp = await incidentServer.getIncidentDetailBase(param);
      console.log('获取到的基本信息：', resp);
      DeviceEventEmitter.emit('showLoading', false);

      if (resp.data) {
        if (resp.data.failureVo.failureDesc) {
          resp.data.failureVo.failureDesc = `${resp.data.failureVo.failureDesc} ${resp.data.failureVo.failureKeywords}`;
        } else {
          resp.data.failureVo.failureDesc = `${resp.data.failureVo.failureKeywords}`;
        }
        if (resp.data.failureVo.failureCause) {
          resp.data.failureVo.failureCause = `${resp.data.failureVo.failureCause} ${resp.data.failureVo.causeKeywords}`;
        } else {
          resp.data.failureVo.failureCause = `${resp.data.failureVo.causeKeywords}`;
        }
        if (resp.data.failureVo.setp) {
          resp.data.failureVo.setp = `${resp.data.failureVo.setp} ${resp.data.failureVo.keywords}`;
        } else {
          resp.data.failureVo.setp = `${resp.data.failureVo.keywords}`;
        }
        // resp.data.failureVo.failureType == '08' && resp.data.failureVo.failureTypeDesc='08';
        if (resp.data.failureVo.failureType == '08') {
          resp.data.failureVo.failureTypeDesc = '设施维修';
        }
        if (resp.data.failureVo.failureType == '09') {
          resp.data.failureVo.failureTypeDesc = '安全隐患';
          if (resp.data.failureVo.failureLevel == 'A') {
            resp.data.failureVo.failureLevelDesc = '重大隐患';
          } else {
            resp.data.failureVo.failureLevelDesc = '一般隐患';
          }
        }
        this.setState({
          pageData: resp.data.failureVo,
          changeParts: resp.data.accyreplacementVOList,
          failurePositions: resp.data.failurePositions,
        }, () => {
          this._getBtnsTypeByBaseData();
        });
      } else {
        console.log('后台无数据！');
      }
    } catch (error) {
      console.log('获取到的基本信息报错：', error);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  _getTab2Info = (id) => {
    try {
      this.setState({
        timeLineLoading: true,
      });
      incidentServer.getIncidentDetailSteps(id).then(resp => {
        console.log('处理轨迹：', resp);
        this.setState({
          tab2Data: resp.data,
          timeLineLoading: false,
        });
      });
    } catch (error) {
      this.setState({
        timeLineLoading: false,
      });
    }
  }

  bindBackEvt = () => {

  }

  _toMianPage = () => {
    if (this.props.navigation) {
      this.props.navigation.goBack();
    } else {
      DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
    }
  }

  _getOpetationBtn = (type) => { // 根绝按钮类型返回不同ReactDom
    switch (type) {
      case '1': // 接收
        return (
          <TouchableNativeFeedback
            onPress={() => this._showAlert('接收？', 'accept')}
          >
            <View
              style={styles.acceptBtn}
            >
              <Image
                source={require('../../../../assets/images/btn-cut-line-xxx.png')}
                style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
                resizeMode="contain"
                resizeMethod="auto"
              />
              <Text style={styles.btnText}>接收</Text>
            </View>
          </TouchableNativeFeedback>
        );
      case '2': // 变更维修班组 / 撤销
        return (
          <View>
            <Image
              source={require('../../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('撤回任务？', 'backToEdit')}
                key={1}
              >
                <View style={styles.changeBranch}>
                  {/* <Text style={styles.btnText}>变更维修班组</Text> */}
                  <Text style={styles.btnText}>撤回</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('直接关闭任务？', 'cancleProblem')}
                key={2}
              >
                <View style={styles.cancle}>
                  {/* 2018.12.4 按钮名称改为直接关闭
                  <Text style={styles.btnText}>撤销任务</Text> */}
                  <Text style={styles.btnText}>直接关闭</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
        );
      case '3': // 退回|维修完成 （维修人员操作）
        return (
          <View>
            <Image
              source={require('../../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={() => this.sendBackByCheck()}
                key={3}
              >
                <View
                  style={styles.sendBack}
                >
                  <Text style={styles.btnText}>退回</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this.complete()}
                key={4}
              >
                <View
                  style={styles.complete}
                >
                  <Text style={styles.btnText}>维修完成</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
        );
      // case '4': // 退回 （申请人操作）
      //   return (
      //     <View>
      //       <TouchableNativeFeedback
      //         onPress={() => this._showAlert('退回', 'returned')}
      //       >
      //         <Image
      //           source={require('../../../../assets/images/btn-cut-line-xxx.png')}
      //           style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
      //           resizeMode="stretch"
      //           resizeMethod="auto"
      //         />
      //         <View
      //           style={styles.returned}
      //         >
      //           <Text style={styles.btnText}>退回</Text>
      //         </View>
      //       </TouchableNativeFeedback>
      //     </View>
      //   );
      case '5': // 验收 （申请人操作）
        return (
          <TouchableNativeFeedback
            onPress={() => { this.checkAndAccept(); }}
          >
            <View
              style={styles.checkAndAccept}
            >
              <Image
                source={require('../../../../assets/images/btn-cut-line-xxx.png')}
                style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
                resizeMode="stretch"
                resizeMethod="auto"
              />
              <Text style={styles.btnText}>验收</Text>
            </View>
          </TouchableNativeFeedback>
        );
      case '6': // 重新申报 直接关闭
        return (
          <View>
            <Image
              source={require('../../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('重新申报任务？', 'reportByRepoter')}
                key={5}
              >
                <View style={styles.changeBranch}>
                  {/* <Text style={styles.btnText}>变更维修班组</Text> */}
                  <Text style={styles.btnText}>重新申报</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('直接关闭任务？', 'cancleProblem')}
                key={6}
              >
                <View style={styles.cancle}>
                  {/* 2018.12.4 按钮名称改为直接关闭
                  <Text style={styles.btnText}>撤销任务</Text> */}
                  <Text style={styles.btnText}>直接关闭</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
        );
      case '7': // 变更维修班组 / 撤销
        return (
          <View>
            <Image
              source={require('../../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('撤回任务？', 'backToEdit')}
                key={7}
              >
                <View style={styles.changeBranch}>
                  {/* <Text style={styles.btnText}>变更维修班组</Text> */}
                  <Text style={styles.btnText}>撤回</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('直接关闭任务？', 'cancleProblem')}
                key={8}
              >
                <View style={styles.cancle}>
                  {/* 2018.12.4 按钮名称改为直接关闭
                  <Text style={styles.btnText}>撤销任务</Text> */}
                  <Text style={styles.btnText}>直接关闭</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this._showAlert('接收？', 'accept')}
                key={9}
              >
                <View style={styles.cancle}>
                  {/* 2018.12.4 按钮名称改为直接关闭
                  <Text style={styles.btnText}>撤销任务</Text> */}
                  <Text style={styles.btnText}>接收</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
        );
      case '8': // 退回|维修完成 （维修人员操作）
        return (
          <View>
            <Image
              source={require('../../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={() => this.sendBackAndStopByCheck()}
                key={10}
              >
                <View
                  style={styles.sendBack}
                >
                  <Text style={styles.btnText}>退回/暂存待办</Text>
                </View>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback
                onPress={() => this.complete()}
                key={11}
              >
                <View
                  style={styles.complete}
                >
                  <Text style={styles.btnText}>维修完成</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
        );
      default:
        return null;
    }
  }

  _showAlert = (info, methodName) => {
    Alert.alert(
      '提示',
      `是否${info}`,
      [
        {
          text: '否',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '是',
          onPress: () => {
            this[methodName]();
          },
        },
      ],
    );
  }

  // 接收
  accept = async () => {
    try {
      let query = {
        handler: global.user.name,
        handlerName: global.user.staff.name,
        failureId: this.state.incidentId, // 故障ID
        stepCode: '04', // 接口的步骤编码
      };
      query = Object.assign(query, this._mobileInfo);
      DeviceEventEmitter.emit('showLoading', true);
      const resp = await incidentServer.incidentHandle(query);
      // DeviceEventEmitter.emit('showLoading', false);
      this._handleServerResponse(resp);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      console.log(error);
    }
  }

  /**
   * 变更维修班族（before 2018.12.4）
   * 撤回（12.4 需求变更）
   * (2019.1.4)需要先请求接口，在决定是否跳转至申报页面
   *
   */
  backToEdit = async () => {
    /* before 2018.12.4 打开维修班组选择面板
    this.setState({
      modalVisible: true,
    });
    */
    try {
      DeviceEventEmitter.emit('showLoading', true);
      let query = {
        handler: global.user.name,
        handlerName: global.user.staff.name,
        failureId: this.state.incidentId, // 故障ID
        stepCode: '07', // 接口的步骤编码
      };
      query = Object.assign(query, this._mobileInfo);
      const resp = await incidentServer.incidentHandle(query);
      DeviceEventEmitter.emit('showLoading', false);
      if (resp.resultCode == '0') { // 成功 跳转到编辑页面
        UtilToast('操作成功', 'success');
        global.navigation.navigate({
          routeName: 'AddIncident',
          params: {
            flag: 'update',
            data: this.state.pageData,
            _refresh: this._refresh,
          },
        });
      } else {
        UtilToast(resp.resultMsg || '操作失败，请重试', 'success');
        this._refresh();
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      this._refresh();
      console.log('error is', error);
    }
  }

  // 撤销（申请人撤销）
  cancleProblem = async () => {
    try {
      let query = {
        failureId: this.state.incidentId, // 故障ID
        stepCode: '03', // 创建的步骤编码
        description: '',
      };
      query = Object.assign(query, this._mobileInfo);
      DeviceEventEmitter.emit('showLoading', true);
      const resp = await incidentServer.incidentHandle(query);
      this._handleServerResponse(resp);
    } catch (error) {
      console.log('撤销 catch:', error);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  // 维修人员退回
  sendBackByCheck = () => {
    global.navigation.navigate({
      routeName: 'submitPage',
      params: {
        type: 'SendBack',
        titleStr: '退回',
        mobileInfo: this._mobileInfo,
        id: this.state.incidentId,
        _refresh: this._refresh,
      },
    });
  }

  // 维修人员退回或暂存待办
  sendBackAndStopByCheck = () => {
    global.navigation.navigate({
      routeName: 'submitPage',
      params: {
        type: 'SendBackAndStop',
        titleStr: '退回/暂存待办',
        mobileInfo: this._mobileInfo,
        id: this.state.incidentId,
        _refresh: this._refresh,
      },
    });
  }

  // 维修完成
  complete = () => {
    global.navigation.navigate({
      routeName: 'submitPage',
      params: {
        type: 'maintainComplete',
        titleStr: '维修完成',
        mobileInfo: this._mobileInfo,
        id: this.state.incidentId,
        _refresh: this._refresh,
        equipObjType: this.state.pageData.objType,
        equipmentId: this.state.pageData.failureType == '08' ? this.state.pageData.facilityId : this.state.pageData.equipmentId,
        facilityId: this.state.pageData.facilityId,
        failureType: this.state.pageData.failureType,
        failureKeywordsId: this.state.pageData.failureKeywordsId,
        deviceMaintOrgId: this.state.pageData.maintOrgId,
      },
    });
  }

  // 申请人退回
  returned = () => {
    alert('申请人退回');
  }

  /**
   * 重新申报
  */
  reportByRepoter = async () => { // 重新申报
    global.navigation.navigate({
      routeName: 'AddIncident',
      params: {
        flag: 'update',
        data: this.state.pageData,
        _refresh: this._refresh,
      },
    });
  }

  // 验收
  checkAndAccept = () => {
    global.navigation.navigate({
      routeName: 'submitPage',
      params: {
        type: 'checkAndAccept',
        titleStr: '验收',
        mobileInfo: this._mobileInfo,
        id: this.state.incidentId,
        _refresh: this._refresh,
      },
    });
  }

  _handleServerResponse = (resp) => {
    if (resp.resultCode == '0') { // 状态码成功
      DeviceEventEmitter.emit('refreshPageEvent'); // 刷新首页列表
      UtilToast('操作成功', 'success');
    } else {
      UtilToast(resp.resultMsg || '操作失败，请重试', 'success');
    }
    setTimeout(() => {
      this._initPage({
        id: this.state.incidentId,
        code: this.state.incidentCode,
        fromNavigation: this.state.navigation,
      });
    }, 1000);
  }

  _showDetaiImage = () => {
    if (this.state.pageData.equipmentImage) {
      return {
        uri: `${incidentServer.getDownloadImg}/${this.state.pageData.equipmentImage}?token=${global.__TOKEN_ACCESS__}`,
      };
    }
    return require('../../../../assets/images/no-pic.png');
  }

  // 判断当前用户是否能又验收的权限
  _canCheckAndAccept = async () => {
    try {
      const resp = await incidentServer.getAcceptPemission(this.state.pageData.failureCode);
      return resp.data;
    } catch (error) {
      console.log('get check mission error,', error);
      return false;
    }
  }

  /**
   * 结合后台数据状态和当前登录人判断展示不同的按钮
   * ("00", "待申报")   6/100 重新申报/不展示
   * ("10", "待接收"),  1/2/100
   * ("20", "已接收"),  3/100
   * ("30", "维修完成") 5/100
   * 100 是没有任何按钮的意思
   */
  _getBtnsTypeByBaseData = async () => { // 结合后台状态和登录人得到按钮类型
    // 当前用户 code
    const userId = global.user.name;

    const safeDepId = global.safeDep && global.safeDep.orgId;

    // 当前用户所在团队ID
    const userOrgId = global.user.organization.id;

    const problemStatus = this.state.pageData.failureStatus; // 故障状态
    const { reporter, failureType } = this.state.pageData; // 申报人ID
    const { maintOrgId } = this.state.pageData;// 指定维修团队ID
    // const handlerId = this.state.pageData.handler;// 处理人ID

    let btnType = '100';
    // 申报状态  需要重新申报
    if (problemStatus == '00') {
      if (this.state.pageData.failureType == '08' || userId == reporter) { // 当前是申报人，要展示重新申报
        btnType = '6';
      }
    }

    // 判断展示待接收按钮
    if (problemStatus == '10') {
      if (this.state.pageData.failureType == '08' && userId == reporter) { // 当前是申报人且是设施维修，要展示 变更维修班族和撤销和接受
        btnType = '7';
      } else if (this.state.pageData.failureType == '09' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '7';
      } else if (this.state.pageData.failureType == '06' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '7';
      } else if (this.state.pageData.failureType == '08') { // 当前不是申报人，但是是设施维修展示接受
        btnType = '1';
      } else if (userId == reporter && failureType == '07') { // 当前是申报人，要展示 变更维修班族和撤销和接受
        btnType = '7';
      } else if (userId == reporter) { // 当前是申报人，要展示 变更维修班族和撤销
        btnType = '2';
      } else if (userOrgId == maintOrgId) { // 当前登陆人是指定维修团队中人 展示接收
        btnType = '1';
      }
    }

    // 判断展示退回和维修完成按钮
    if (problemStatus == '20') {
      if (this.state.pageData.failureType == '08' || userOrgId == maintOrgId) { // 接收状态 当前登陆人班组是指定维修团队的人，展示维修完成/退回
        btnType = '8';
      } else if (this.state.pageData.failureType == '09' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '8';
      } else if (this.state.pageData.failureType == '06' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '8';
      } else if (userId == reporter && failureType == '07') {
        btnType = '8';
      } else if (userId == reporter && maintOrgId == '-1') {
        btnType = '8';
      }
      // if (userId == handlerId) { // 当前登陆人是处理人 展示维修完成/退回按钮
      //   return '3';
      // }
    }

    // 判断展示退回/暂存待办和维修完成按钮
    if (problemStatus == '40') {
      if (this.state.pageData.failureType == '08' || userOrgId == maintOrgId) { // 接收状态 当前登陆人班组是指定维修团队的人，展示维修完成/退回
        btnType = '3';
      } else if (this.state.pageData.failureType == '09' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '3';
      } else if (this.state.pageData.failureType == '06' && safeDepId == maintOrgId) { // 安全隐患
        btnType = '3';
      } else if (userId == reporter && failureType == '07') {
        btnType = '3';
      }
    }

    // 判断展示验收按钮
    if (problemStatus == '30') {
      // const flag = this.state.pageData.failureType == '08' ? true : await this._canCheckAndAccept();
      // if (this.state.pageData.failureType == '09' || this.state.pageData.failureType == '06') { // 安全隐患
      //   if (userId == reporter) {
      //     btnType = '5';
      //   }
      // } else if (this.state.pageData.failureType == '08') { // 查询后台当前人是否有验收的权限
      //   btnType = '5';
      // } else if (failureType == '07') {
      //   if (userId == reporter) {
      //     btnType = '5';
      //   }
      // } else {
      //   const flag = await this._canCheckAndAccept();
      //   if (flag) {
      //     btnType = '5';
      //   }
      // }
      if (userId == reporter) {
        btnType = '5';
      } else {
        const flag = await this._canCheckAndAccept();
        if (flag) {
          btnType = '5';
        }
      }
    }

    this.setState({
      btnType,
    });
  }

  _cancelModal = () => {
    this.setState({
      modalVisible: false,
    });
  }

  _choiceConfirm = (item) => {
    this._cancelModal();
    this.changeToServser(item[0]);
  }

  // 变更维修班组提交到后台
  changeToServser = async (data) => {
    if (!data) {
      UtilToast('没有选择数据，请选择班组', 'danger');
      return;
    }
    try {
      const params = {
        failureId: this.state.incidentId,
        maintOrgId: data.id,
      };
      DeviceEventEmitter.emit('showLoading', true);
      const resp = await incidentServer.changeMaintOrg(params);
      this._handleServerResponse(resp);
    } catch (error) {
      console.log('变更维修班组到server:', error);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  _getChangeBranchDom = (type) => {
    if (type == '2' && this.state.modalVisible) {
      return (
        <FormSearchChoice
          onClose={this._cancelModal}
          searchUri={this.searchUri}
          type="radio"
          choiceConfirm={this._choiceConfirm}
        />
      );
    }
    return null;
  }

  /**
  * 根绝当前数据展示不同的基本信息内容
  */
  _showBaseInfoType = () => {
    const { failureStatus } = this.state.pageData;
    if (failureStatus == '30') { // 维修完成
      return 'twoBlock'; // 展示两块 基本信息和维修信息
    }
    if (failureStatus == '03') { // 验收关闭
      return 'threeBlock'; // 展示三块 基本信息和维修信息和验收信息
    }
    return 'oneBlock'; // 仅仅展示维修信息
  }

  _tabChange = () => {
    if (this._tabRef && this._tabRef.state.currentPage === 1) {
      this._timelineTab.changeToThisTab();
    }
  }

  _showEquName = (text, statusDesc) => {
    if (!text) {
      return (
        <Badge style={[styles.badge]}>
          <Text style={{ color: '#207aff', fontSize: 10 }}>
            {statusDesc}
          </Text>
        </Badge>
      );
    }
    const list = [];
    for (let i = 0, len = text.length; i < len; i += 1) {
      list.push(
        <Text key={i} style={styles.colorWhite}>{text[i]}</Text>,
      );
    }
    list.push(
      <Badge style={[styles.badge]} key="badgeStatus">
        <Text style={{ color: '#207aff', fontSize: 10 }}>
          {statusDesc}
        </Text>
      </Badge>,
    );
    return list;
  }

  toDevice = () => {
    // global.navigation.navigate({ routeName: 'About', params: { id: item._id } });
    if (this.state.pageData.failureType != '08' && this.state.pageData.equipmentId) {
      const params = {
        fromNavigation: true,
        id: this.state.pageData.equipmentId,
        objType: this.state.pageData.objType,
        equipmentCode: this.state.pageData.equipmentCode,
      };
      global.navigation.navigate({ routeName: 'deviceInfo', params });
    }
  }

  _tabRef

  _timelineTab

  render() {
    const { btnType } = this.state;
    const baseInfoType = this._showBaseInfoType();
    // const type = '3';
    return (
      <View style={styles.container}>
        {this._getChangeBranchDom(btnType)}
        <View style={styles.headerContainer}>
          <View style={styles.headerTitle}>
            <TouchableWithoutFeedback onPress={this._toMianPage}>
              <View style={{ padding: 5 }}>
                <ZlstIcon
                  style={styles.backIcon}
                  name="fanhui"
                  size={20}
                  color={fontColor}
                />
              </View>
            </TouchableWithoutFeedback>
            <Text style={styles.headerText}>{this.state.pageData.failureType == '09' ? '隐患详情' : '故障详情'}</Text>
            <View style={styles.rightOperate} />
          </View>
          <TouchableWithoutFeedback onPress={() => this.toDevice()}>
            <View style={styles.headerInfo}>
              <View style={styles.imageContent}>
                <Image style={styles.imageCls} source={this._showDetaiImage()} />
              </View>
              <View style={styles.otherSimpleInfo}>
                <View style={styles.deviceStatus}>
                  {
                    this.state.pageData.failureType == '09' && this._showEquName(
                      this.state.pageData.hiddenDangerType == '3' ? `类型：${this.state.pageData.facilityTypeName}` : '安全隐患',
                      this.state.pageData.failureStatusDesc,
                    )
                  }
                  {
                    this.state.pageData.failureType !== '09' && this._showEquName(
                      this.state.pageData.failureType == '08' ? `类型：${this.state.pageData.facilityTypeName}` : this.state.pageData.equipmentName,
                      this.state.pageData.failureStatusDesc,
                    )
                  }
                  {/* <Text style={[styles.colorWhite, { flex: 1 }]}>
                    {this.state.pageData.equipmentName || ''}
                  </Text>
                  <Badge style={[styles.badge]}>
                    <Text style={{ color: '#207aff', fontSize: 10 }}>
                      {this.state.pageData.failureStatusDesc}
                    </Text>
                  </Badge> */}
                </View>
                <View>
                  {
                    this.state.pageData.failureType == '09' && this.state.pageData.hiddenDangerType == '3' && (
                      <Text style={styles.colorWhite}>{this.state.pageData.facilityName ? this.state.pageData.facilityName : ''}</Text>
                    )
                  }
                  {
                    this.state.pageData.failureType !== '09' && (
                      <Text style={styles.colorWhite}>{this.state.pageData.failureType == '08' ? `名称：${this.state.pageData.facilityName ? this.state.pageData.facilityName : ''}` : `设备编号：${this.state.pageData.equipmentCode ? this.state.pageData.equipmentCode : ''}`}</Text>
                    )
                  }
                </View>
                {/* <View>
                  <Text style={styles.colorWhite}>使用单位：{this.state.pageData.maintOrgIdDesc}</Text>
                </View> */}
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
        <View style={styles.tabContent}>
          <Tabs
            page={this.state.defaultPageIndex}
            tabBarUnderlineStyle={styles.tabBarUnderlineStyle}
            onChangeTab={() => this._tabChange()}
            ref={(ref) => { this._tabRef = ref; }}
          >
            <Tab heading={this.state.pageData.failureType == '09' ? '隐患信息' : '故障信息'}>
              <ScrollView style={{ backgroundColor: Theme.myPrimary }}>
                {/* {this._showTitle()} */}
                <Tab1
                  data={this.state.pageData}
                  baseInfoType={baseInfoType}
                  changePartsData={this.state.changeParts}
                  failurePositions={this.state.failurePositions}
                />
              </ScrollView>
            </Tab>
            <Tab heading="处理轨迹">
              <ScrollView style={{ backgroundColor: Theme.myPrimary }}>
                <Tab2
                  data={this.state.tab2Data}
                  showLoading={this.state.timeLineLoading}
                  ref={(ref) => { this._timelineTab = ref; }}
                  failureCause={this.state.pageData.failureCause}
                />
              </ScrollView>
            </Tab>
          </Tabs>
        </View>
        <View style={styles.operationBtns}>
          {this._getOpetationBtn(btnType)}
        </View>
      </View>
    );
  }
}

export default Info;
